require_relative 'multiclient_tcp_server'
# This references the Dropbox SDK gem install with "gem install dropbox-sdk"
require 'dropbox_sdk'

# Get your app key and secret from the Dropbox developer website
APP_KEY = 'nr72yl7h35lhuzh'
APP_SECRET = 'z3b1xmryn3lado8'

# ACCESS_TYPE should be ':dropbox' or ':app_folder' as configured for your app
ACCESS_TYPE = :app_folder

srv = MulticlientTCPServer.new( 2000, 1, true )

loop do
    if sock = srv.get_socket
        # a message has arrived, it must be read from sock
        message = sock.gets( "\r\n" ).chomp( "\r\n" )
        # arbitrary examples how to handle incoming messages:
        if message == 'quit'
            raise SystemExit
        elsif message =~ /^puts (.*)$/
            puts "message from #{sock.peeraddr.join(':')}: '#{$1}'"
        elsif message =~ /^echo (.*)$/
      # send something back to the client
            sock.write( "server echo: '#{$1}'\r\n" )
        
        elsif message == 'dropbox'
            session = DropboxSession.new(APP_KEY, APP_SECRET)

            session.get_request_token
 
            authorize_url = session.get_authorize_url

            # Make the user sign in and authorize this token
            puts "AUTHORIZING", authorize_url
            puts "Please visit that web page and hit 'Allow', then hit Enter here."
            gets

            # This will fail if the user did not visit the above URL and hit 'Allow'
            session.get_access_token

            client = DropboxClient.new(session, ACCESS_TYPE)
            puts "linked account:", client.account_info().inspect

            file = open('working-draft.txt')
            response = client.put_file('/magnum-opus.txt', file)
            puts "uploaded:", response.inspect

            file_metadata = client.metadata('/magnum-opus.txt')
            puts "metadata:", file_metadata.inspect

            contents, metadata = client.get_file_and_metadata('/magnum-opus.txt', rev='303eca74c')
            open('magnum-opus.txt', 'w') {|f| f.puts contents }
            puts metadata
            sock.write("dropbox successed")
        else
            puts "unexpected message from #{sock.peeraddr}: '#{$1}'"
        end
    else
        sleep 0.01 # free CPU for other jobs, humans won't notice this latency
    end
end